package com.dacool.fragment;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Color;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.dacool.app.sale.R;
import com.dacool.http.BaseRequest;
import com.dacool.http.BaseRequest.ResponseHandler;
import com.dacool.http.GetCoolMoneyRequest;
import com.dacool.model.CoolBLogEntry;
import com.dacool.util.ViewUtils;

public class CoolBFragment extends BaseFragment implements OnClickListener {

	private ArrayList<CoolBLogEntry> outlogEntries = new ArrayList<CoolBLogEntry>();
	private ArrayList<CoolBLogEntry> inLogEntries = new ArrayList<CoolBLogEntry>();
	private ArrayList<CoolBLogEntry> displayEntries = new ArrayList<CoolBLogEntry>();

	private Button buttonIn;
	private Button buttonOut;
	private View indicator1;
	private View indicator2;
	private ListView listView;
	// private TextView coolbSum;

	private int selectedTab = 0;

	private ArrayAdapter<CoolBLogEntry> mAdapter;

	@Override
	protected int myLayoutID() {
		// TODO Auto-generated method stub
		return R.layout.frag_coolb;
	}

	@Override
	protected View myView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected boolean showDefaultSecondLeftButton() {
		// TODO Auto-generated method stub
		return true;
	}

//	@Override
//	protected boolean showDefaultLeftButton() {
//		return true;
//	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewCreated(view, savedInstanceState);
		buttonIn = ViewUtils.findViewById(view, R.id.income);
		buttonOut = ViewUtils.findViewById(view, R.id.outgoing);
		buttonIn.setOnClickListener(this);
		buttonOut.setOnClickListener(this);
		indicator1 = ViewUtils.findViewById(view, R.id.tabindicator1);
		indicator2 = ViewUtils.findViewById(view, R.id.tabindicator2);
		listView = ViewUtils.findViewById(view, R.id.coolblog);
		// coolbSum = ViewUtils.findViewById(view, R.id.coolbAmount);
		mAdapter = new ArrayAdapter<CoolBLogEntry>(getActivity(), 0) {
			@Override
			public int getCount() {
				// TODO Auto-generated method stub
				return displayEntries.size();
			}

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				if (convertView == null) {
					View view = LayoutInflater.from(getContext()).inflate(
							R.layout.coolblogitem, null);
					ViewHolder holder = new ViewHolder();
					holder.icon = ViewUtils.findViewById(view, R.id.imageView);
					holder.textView1 = ViewUtils.findViewById(view,
							R.id.timeLabel);
					holder.textView2 = ViewUtils.findViewById(view,
							R.id.idlabel);
					holder.textView3 = ViewUtils.findViewById(view,
							R.id.coolbLabel);
					view.setTag(holder);
					convertView = view;
				}
				ViewHolder holder = (ViewHolder) convertView.getTag();
				CoolBLogEntry entry = displayEntries.get(position);
				holder.textView1.setText(entry.logTime);
				holder.textView2
						.setText(String.format("订单号 %s", entry.orderID));
				if (entry.coolbAmount > 0) {
					holder.textView3.setText(String.format("+ %d",
							entry.coolbAmount));
					holder.textView3.setTextColor(0xff85c400);
				} else {
					holder.textView3.setText(String.format("- %d",
							-entry.coolbAmount));
					holder.textView3.setTextColor(getResources().getColor(
							R.color.price_color));
				}

				return convertView;
			}

			class ViewHolder {
				private ImageView icon;
				private TextView textView1;
				private TextView textView2;
				private TextView textView3;
			}
		};
		initDisplayEntries();
		listView.setAdapter(mAdapter);
	}

	private void initDisplayEntries() {
		indicator1.setBackgroundColor(selectedTab == 1 ? Color.TRANSPARENT
				: 0xff85c400);
		indicator2.setBackgroundColor(selectedTab == 0 ? Color.TRANSPARENT
				: 0xff85c400);
		buttonIn.setEnabled(selectedTab == 1);
		buttonOut.setEnabled(selectedTab == 0);
		displayEntries = selectedTab == 0 ? inLogEntries : outlogEntries;
	}

	private void loadCoolB(final int type) {
		showProgressDialog(null, false);
		new GetCoolMoneyRequest().setType(selectedTab + 1)
				.setHandler(new ResponseHandler() {

					@Override
					public void handleResponse(BaseRequest request,
							int statusCode, String errorMsg, String response) {
						CoolBFragment.this.dismissProgressDialog();
						if (statusCode != 200) {
							return;

						}
						/**
						 * memberId" : 15, "toMemberId" : 18, "orderId" :
						 * 2014042620270316, "coolMoney" : 100, "type" : 1,
						 * "createTime" : "2014-05-06 12:13"
						 */
						boolean success = false;
						try {
							JSONObject json = new JSONObject(response);
							success = json.optBoolean("success", false);
							if (!success)
								return;
							if (type == 1)
								inLogEntries.clear();
							else
								outlogEntries.clear();
							JSONArray array = json.getJSONArray("data");
							for (int i = 0; i < array.length(); i++) {
								JSONObject obj = array.getJSONObject(i);
								CoolBLogEntry entry = new CoolBLogEntry();
								entry.logTime = obj.getString("createTime");
								entry.coolbAmount = obj.getInt("coolMoney")
										* (type == 2 ? -1 : 1);
								entry.orderID = obj.getString("orderId");
								if (type == 1)
									inLogEntries.add(entry);
								else
									outlogEntries.add(entry);
							}

						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} finally {
							ViewUtils.runInMainThread(new Runnable() {

								@Override
								public void run() {
									// TODO Auto-generated method stub
									if (type == 1)
										displayEntries = inLogEntries;
									else
										displayEntries = outlogEntries;
									mAdapter.notifyDataSetChanged();
								}
							});
						}

					}
				}).start();
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		loadCoolB(selectedTab + 1);
	}

	@Override
	public void onClick(View v) {
		if (v == buttonIn || v == buttonOut) {
			selectedTab = v == buttonIn ? 0 : 1;
			initDisplayEntries();
			mAdapter.notifyDataSetChanged();
			loadCoolB(selectedTab + 1);
		}
		super.onClick(v);
	}

	@Override
	public String titleText() {
		// TODO Auto-generated method stub
		return "我的库币";
	}
}
